package com.xuxin.baby.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.lxj.xpopup.XPopup;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.xuxin.baby.R;
import com.xuxin.baby.adapter.UserChildAdapter;
import com.xuxin.baby.base.BaseActivity;
import com.xuxin.baby.base.BaseConstant;
import com.xuxin.baby.bean.BaseBean;
import com.xuxin.baby.bean.UserChildBean;
import com.xuxin.baby.contract.UserChildContract;
import com.xuxin.baby.contract.UserChildDataContract;
import com.xuxin.baby.event.MainFragmentEvent;
import com.xuxin.baby.popup.ConfirmPopup;
import com.xuxin.baby.presenter.UserChildDataPresenter;
import com.xuxin.baby.presenter.UserChildPresenter;
import com.xuxin.baby.utils.ACache;
import com.xuxin.baby.utils.BaseUtils;
import com.xuxin.baby.utils.RecycleUtils;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by xu_xin
 * Created on 2020.08.05 0005
 * 我的宝宝
 */
public class UserChildActivity extends BaseActivity implements UserChildContract.View, UserChildDataContract.View {
    private final UserChildContract.Presenter presenter = new UserChildPresenter(this);
    private final UserChildDataContract.Presenter presenter2 = new UserChildDataPresenter(this);
    @BindView(R.id.title_left)
    ImageView title_left;
    @BindView(R.id.title_right)
    ImageView title_right;
    @BindView(R.id.title_name)
    TextView title_name;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smart_refresh;
    @BindView(R.id.smart_recycle)
    RecyclerView smart_recycle;

    private UserChildAdapter myAdapter;
    private String memberId;//用户ID
    private String tenantId;//租户id
    private String token;//授权token

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_smart);
    }

    @Override
    public void initView() {
        title_name.setText("我的宝宝");
        //刷新加载
        smart_refresh.setEnableLoadMore(false);
        smart_refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                LogUtils.e("onRefresh");
                myAdapter.setList(null);
                handler.sendEmptyMessage(0);
            }
        });
        RecycleUtils.init(smart_recycle);
        myAdapter = new UserChildAdapter();
        smart_recycle.setAdapter(myAdapter);
        myAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                try {
                    Bundle bundle = new Bundle();
                    bundle.putString("childId", myAdapter.getData().get(position).getId());
                    bundle.putString("avatar", myAdapter.getData().get(position).getAvatar());
                    bundle.putString("nickname", myAdapter.getData().get(position).getNickname());
                    bundle.putString("birthday", BaseUtils.getTime(myAdapter.getData().get(position).getBirthday()));
                    bundle.putString("sex", myAdapter.getData().get(position).getSex());
                    bundle.putString("height", myAdapter.getData().get(position).getHeight());
                    bundle.putString("weight", myAdapter.getData().get(position).getWeight());
                    bundle.putString("headCircle", myAdapter.getData().get(position).getHeadCirc());
                    ActivityUtils.startActivityForResult(bundle, UserChildActivity.this, UserChildDataActivity.class, 200);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        myAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if (myAdapter.getData().size() > 1) {
                    new XPopup.Builder(context)
                            .dismissOnTouchOutside(true)
                            .dismissOnBackPressed(true)
                            .asCustom(new ConfirmPopup(context, "确定要删除宝宝吗？", new ConfirmPopup.OnConfirmListener() {
                                @Override
                                public void onConfirm() {
                                    try {
                                        Message message = Message.obtain();
                                        message.what = 1;
                                        message.obj = myAdapter.getData().get(position).getId();
                                        popup.setTitle("正在删除中...").show();
                                        handler.sendMessage(message);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        dismiss();
                                    }
                                }
                            })).show();
                } else {
                    ToastUtils.showShort("最少要有一名宝宝。");
                }
                return false;
            }
        });

        View footer = View.inflate(context, R.layout.item_user_child_footer, null);
        myAdapter.addFooterView(footer);
        footer.findViewById(R.id.item_user_child_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (myAdapter.getData().size() < 5) {
                    ActivityUtils.startActivityForResult(UserChildActivity.this, UserChildDataActivity.class, 200);
                } else {
                    ToastUtils.showShort("您已经添加太多宝宝了");
                }
            }
        });
    }

    @Override
    public void initData() {
        ACache aCache = ACache.get(this);
        memberId = aCache.getAsString(BaseConstant.memberId);
        tenantId = aCache.getAsString(BaseConstant.tenantId);
        token = aCache.getAsString(BaseConstant.token);
        smart_refresh.autoRefresh();
    }

    @Override
    public void onComplete() {
        smart_refresh.finishRefresh();
        smart_refresh.finishLoadMore();
        dismiss();
    }

    @Override
    @OnClick({R.id.title_left})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.title_left) {
            finish();
        }
    }

    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 0) {
                presenter.getUserChild(tenantId, token, memberId);
            } else if (msg.what == 1) {
                presenter2.deleteUserChild(tenantId, token, (String) msg.obj);
            }
            return false;
        }
    });

    @Override
    public void onSuccess(UserChildBean userChildBean) {
        myAdapter.setList(userChildBean.getResult().getItems());
    }

    /**
     * 删除成功
     */
    @Override
    public void onSuccess(BaseBean baseBean) {
        EventBus.getDefault().post(new MainFragmentEvent());
        myAdapter.setList(null);
        handler.sendEmptyMessage(0);
    }
}